package service

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"guns-go/factory"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
	"guns-go/model/response"
	"guns-go/utils"
)

func DeleteSysVisitLog() error {

	tx := global.GVA_DB.Begin()

	err := tx.Where("1=1").Delete(model.SysVisLog{}).Error

	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func SaveSysVisitLog(sysVisitLog *model.SysVisLog) error {
	// 必须要先声明defer，否则不能捕获到panic异常
	defer func() {
		if err := recover(); err != nil {
			// 这里的err其实就是panic传入的内容
			fmt.Println(err)
		}
	}()

	return global.GVA_DB.Create(sysVisitLog).Error
}

func ExecuteLoginLog(c *gin.Context) error {

	err, sysVisitLog := genBaseSysVisLog(c)

	if err != nil {
		return err
	}

	factory.CreateSysLoginLog(c)

	//保存
	go SaveSysVisitLog(sysVisitLog)

	return nil
}

func ExecuteExitLog(c *gin.Context) error {

	err, sysVisitLog := genBaseSysVisLog(c)

	if err != nil {
		return err
	}

	factory.CreateSysExitLog(c)

	//保存
	go SaveSysVisitLog(sysVisitLog)

	return nil
}

func genBaseSysVisLog(c *gin.Context) (error, *model.SysVisLog) {

	if c != nil {
		ip := c.ClientIP()
		address := ""
		browser := c.Request.UserAgent()
		os := ""

		sysVisLog := factory.GenBaseSysVisLog(ip, address, browser, os)
		return nil, sysVisLog
	} else {
		return errors.New("当前请求参数为空或数据缺失，请联系管理员"), nil
	}
}

func SysVisitLogPage(sysVisLogParam *request.SysVisLogParam, c *gin.Context) (err error, result *response.PageResult) {

	var sysVisLogSlice []*model.SysVisLog
	db := global.GVA_DB

	if sysVisLogParam != nil {

		//根据名称模糊查询
		if sysVisLogParam.Name != "" {
			db = db.Where("name like ?", "%"+sysVisLogParam.Name+"%")
		}

		//根据操作类型查询
		if sysVisLogParam.VisType != nil {
			db = db.Where("vis_type =  ?", sysVisLogParam.VisType)
		}

		//根据是否成功查询
		if sysVisLogParam.Success != "" {
			db = db.Where("success =  ?", sysVisLogParam.Success)
		}
	}
	var totalCount int64

	err = db.Find(&sysVisLogSlice).Count(&totalCount).Error

	if err != nil {
		return err, nil
	}

	pageNo, pageSize, db := utils.DefaultPage(c, db)

	err = db.Find(&sysVisLogSlice).Error

	if err != nil {
		return err, nil
	}

	return err, utils.CoverToPageResult(pageNo, pageSize, totalCount, sysVisLogSlice)
}
